﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EasySL.Core;
using EasySL.UI.Controls;
using EasySL.Controls;

namespace EasySL.UI.Controls
{
    public delegate void LoginSuccess(string userName);
    
    public partial class Login : UserControl
    {

        public LoginSuccess OnLoginSuccess { get; set; }
        
        public Login()
        {
            InitializeComponent();

            this.login.OnClose += new RoutedEventHandler(this.ClosePanel);
            this.submit.Click += new RoutedEventHandler(submit_Click);

            this.userLoginTask = new Task();
            userLoginTask.BeforeStart += new EventHandler<EventArgs>(userLoginTask_BeforeStart);
            userLoginTask.Callback += new GetDataAsyncCompleted(this.UserLoginCallBack);
        }

        //prepare the mothedName, returnType
        //which match the method of EasySL.Service/DataService.Method.cs
        void userLoginTask_BeforeStart(object sender, EventArgs e)
        {
            Task task = sender as Task;
            task.MethodName = "UserLogin";
            task.ReturnType = typeof(bool);
            task.SetParameter("userName", this.userName.Text.Trim());
            task.SetParameter("password", this.password.Password.Trim());

            this.activity.IsActive = true;
        }

        //in the callback, we could update UI
        public void UserLoginCallBack(Response response)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                bool succeed = (bool)response.Data;

                if (succeed)
                {
                    this.Visibility = Visibility.Collapsed;

                    if (this.OnLoginSuccess != null)
                        OnLoginSuccess(this.userName.Text);
                }
                else
                {
                    this.notice.Visibility = Visibility.Visible;
                }

                this.activity.IsActive = false;
            });

            
            
        }

        //begin userLoginTask
        void submit_Click(object sender, RoutedEventArgs e)
        {
            this.userLoginTask.Start();
        }

        public void ClosePanel(object sender, RoutedEventArgs e)
        {
            this.login.Opacity = 0;
        }

        private Task userLoginTask;
    }
}
